import 'dart:convert';
import 'dart:core';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:ecy_app_flutter/ecycommon/EcyAPI.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:ecy_app_flutter/main.dart';
import 'package:ecy_app_flutter/routes/login/common/DateUtil.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import '../../EcyRouter.dart';
import '../../constant/color_constant.dart';
import '../../ecycommon/EcyCommonWidgets.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyStorage.dart';
import '../../ecycommon/utils/EcyUserUtil.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../../user/model/EcyUserModel.dart';
import '../mainTabPage.dart';
import 'common/ProfileBirthdayPicker.dart';

/// 选择兴趣后设置昵称页面
class EcyRegisterSettingPage extends EcyCommonBaseWidget {
  EcyRegisterSettingPage();

  @override
  _EcyRegisterSettingPageState createState() {
    return _EcyRegisterSettingPageState(this);
  }
}

class _EcyRegisterSettingPageState extends EcyCommonBaseWidgetState
    with SingleTickerProviderStateMixin {
  late EcyCommonBaseWidget controller;

  _EcyRegisterSettingPageState(EcyCommonBaseWidget vc) {
    controller = vc;
  }
  bool loadingFlag = false;
  late AnimationController _controller;
  final _formKey = GlobalKey<FormState>();
  final _nicknameController = TextEditingController();
  final _signatureController = TextEditingController();
  final _selectedGenderController = TextEditingController();
  final _birthdayController = TextEditingController();

  List<String> genderList = ["男", "女", "其他"];
  int _selectedGender = 0;
  late int _selectedGenderIndex;
  String _birthday = "";

  String avatarUrl = "";
  //头像
  Widget avatar = Image.asset('assets/images/profile.png', width: 120);
  //相机图标
  Widget camera = Image.asset('assets/images/camera2.png', width: 38);
  final ImagePicker _picker = ImagePicker();

  Future<void> _pickImage() async {
    final pickedFile =
        await _picker.pickImage(source: ImageSource.gallery); // 从相册选择图片
    // final pickedFile = await _picker.pickImage(source: ImageSource.camera); // 从相机选择图片
    if (pickedFile != null) {
      // 后端接收文件的参数名为 file
      FormData formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(
          pickedFile.path,
        ),
      });
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/user/avatar", formData);
      print("response" + response.toString());

      if (response != null) {
        setState(() {
          avatarUrl = response["data"];
        });

        EcyStorage.getString(EcyUserUtil.kLoginedUserInfo).then((value) {
          if (value != null) {
            EcyUserModel userModel = EcyUserModel.fromJson(json.decode(value));
            userModel.avatar = response["data"];
            EcyStorage.setString(
                EcyUserUtil.kLoginedUserInfo, json.encode(userModel));
          }
        });
      }
    }
  }

  _loading() {
    setState(() {
      loadingFlag = true;
    });
  }

  void saveUserInfo() async {
    if (_nicknameController.text.length < 2) {
      EasyLoading.showToast("昵称最少两个字符", duration: const Duration(seconds: 1));
      return;
    }
    if (loadingFlag) {
      return;
    }

    _loading();

    try {
      Map<String, dynamic> body = {
        "nickname": _nicknameController.text,
        "signature": _signatureController.text,
        "gender": _selectedGenderIndex, // 0 男 1 女 2 其他
        "birthday": _birthdayController.text.isNotEmpty
            ? "${_birthdayController.text} 00:00:00"
            : "",
      };
      var response =
          await EcyRequestbasemanager().put(EcyAPI.saveAppUser.url, body);
      if (response != null) {
        //模型自动解析
        var resp = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (resp != null) {
          if (resp.code == 0 || resp.code == 200) {
            EcyStorage.getString(EcyUserUtil.kLoginedUserInfo).then((value) {
              if (value != null) {
                EcyUserModel userModel =
                    EcyUserModel.fromJson(json.decode(value));
                if (response['data'] != null) {
                  userModel.nickname = response['data']["nickname"];
                  userModel.signature = response['data']["signature"];
                  _nicknameController.text = userModel.nickname??"";
                  _signatureController.text = userModel.signature??"";
                } else {
                  userModel.nickname = _nicknameController.text;
                  userModel.signature = _signatureController.text;
                }
                userModel.gender = _selectedGenderIndex;
                userModel.birthday = _birthdayController.text;
                EcyStorage.setString(
                    EcyUserUtil.kLoginedUserInfo, json.encode(userModel));
              }
              Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(
                    builder: (context) => ContainPage(
                          key: const Key("containPage"),
                          appLinks: gAppLinks,
                        )),
                (Route<dynamic> route) => false,
              );
            });
          } else {
            EasyLoading.showToast(resp.msg ?? "请稍后再试",
                duration: const Duration(seconds: 1));
          }
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 1));
      EcyLogger.log(e.toString());
    } finally {
      setState(() {
        loadingFlag = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(); // 无限循环
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        child: KeyboardDismisser(
            gestures: const [
              GestureType.onTap,
              GestureType.onPanUpdateDownDirection
            ],
            child: Scaffold(
              resizeToAvoidBottomInset: false,
              backgroundColor: ColorConstant.White,
              appBar: PreferredSize(
                  preferredSize: const Size.fromHeight(44),
                  child: AppBar(
                      backgroundColor: ColorConstant.White,
                      leadingWidth: 120,
                      leading: GestureDetector(
                        onTap: () {
                          EcyRouter.pop(context, "");
                        },
                        child: const Padding(
                          padding: EdgeInsets.only(top: 12),
                          child: Text(
                            '   上一步',
                            style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w700,
                                letterSpacing: 1,
                                fontSize: 16,
                                color: Color.fromRGBO(0, 0, 0, 0.85)),
                          ),
                        ),
                      ),
                      actions: [
                        GestureDetector(
                            onTap: () {
                              Navigator.of(context).pushAndRemoveUntil(
                                MaterialPageRoute(
                                    builder: (context) => ContainPage(
                                          key: const Key("containPage"),
                                          appLinks: gAppLinks,
                                        )),
                                (Route<dynamic> route) => false,
                              );
                            },
                            child: const Text(
                              '跳过  ',
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w700,
                                  letterSpacing: 1,
                                  fontSize: 16,
                                  color: Color.fromRGBO(0, 0, 0, 0.85)),
                            )),
                      ])),
              body: Container(
                color: const Color(0xFFFFFFFF),
                child: Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        const Padding(padding: EdgeInsets.only(top: 20)),
                        SizedBox(
                          width: 120,
                          height: 120,
                          child: ClipOval(
                              child: CachedNetworkImage(
                            width: 120.w,
                            height: 120.w,
                            imageUrl: avatarUrl,
                            imageBuilder: (context, imageProvider) => Container(
                              decoration: BoxDecoration(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(36.r)),
                                  image: DecorationImage(
                                      image: imageProvider, fit: BoxFit.cover)),
                            ),
                            placeholder: (context, url) => avatar,
                            errorWidget: (context, url, error) => avatar,
                          )),
                        ),
                        Transform.translate(
                          offset: const Offset(40.0, -40.0),
                          child: GestureDetector(
                            child: camera,
                            onTap: () {
                              _pickImage();
                            },
                          ),
                        ),
                        Transform.translate(
                          offset: const Offset(0.0, -20.0),
                          child: Column(
                            children: [
                              Text('昵称',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w700,
                                    fontSize: 18.sp,
                                  )),
                              Padding(
                                padding: const EdgeInsets.only(
                                    left: 40, top: 5, right: 40),
                                child: TextField(
                                  controller: _nicknameController,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: InputDecoration(
                                    isDense: true,
                                    filled: true,
                                    fillColor: const Color(0xFFF5F5F5),
                                    hintText: "输入一下昵称吧",
                                    hintStyle: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w700,
                                      fontSize: 14.sp,
                                    ),
                                    border: OutlineInputBorder(
                                      borderRadius:
                                          BorderRadius.circular(50.0), // 边框圆角
                                      borderSide: const BorderSide(
                                          width: 0, style: BorderStyle.none),
                                    ),
                                  ),
                                  onSubmitted: (value) {
                                    FocusScope.of(context).unfocus();
                                  },
                                ),
                              ),
                              const Padding(padding: EdgeInsets.only(top: 5)),
                              Text('性别',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w700,
                                    fontSize: 18.sp,
                                  )),
                              Padding(
                                padding: const EdgeInsets.only(
                                    left: 40, top: 5, right: 40),
                                child: TextField(
                                  readOnly: true,
                                  // enableInteractiveSelection: false,
                                  onTap: () {
                                    _showGenderBottomSheet(context);
                                  },
                                  controller: _selectedGenderController,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: InputDecoration(
                                    isDense: true,
                                    filled: true,
                                    fillColor: const Color(0xFFF5F5F5),
                                    hintText: "请选择",
                                    hintStyle: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w700,
                                      fontSize: 14.sp,
                                    ),
                                    border: OutlineInputBorder(
                                      borderRadius:
                                          BorderRadius.circular(50.0), // 边框圆角
                                      borderSide: const BorderSide(
                                          width: 0, style: BorderStyle.none),
                                    ),
                                  ),
                                  onSubmitted: (value) {
                                    FocusScope.of(context).unfocus();
                                  },
                                ),
                              ),
                              const Padding(padding: EdgeInsets.only(top: 5)),
                              Text('生日',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w700,
                                    fontSize: 18.sp,
                                  )),
                              Padding(
                                padding: const EdgeInsets.only(
                                    left: 40, top: 5, right: 40),
                                child: TextField(
                                  readOnly: true,
                                  // enableInteractiveSelection: false,
                                  onTap: () {
                                    _showbirthdayBottomSheet(context);
                                  },
                                  controller: _birthdayController,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: InputDecoration(
                                    isDense: true,
                                    filled: true,
                                    fillColor: const Color(0xFFF5F5F5),
                                    hintText: "请选择",
                                    hintStyle: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w700,
                                      fontSize: 14.sp,
                                    ),
                                    border: OutlineInputBorder(
                                      borderRadius:
                                          BorderRadius.circular(50.0), // 边框圆角
                                      borderSide: const BorderSide(
                                          width: 0, style: BorderStyle.none),
                                    ),
                                  ),
                                  onSubmitted: (value) {
                                    FocusScope.of(context).unfocus();
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    )),
              ),
              bottomNavigationBar: BottomAppBar(
                height: 60,
                elevation: 0,
                padding: EdgeInsets.zero,
                color: Colors.white,
                // shape: CircularNotchedRectangle(), // 底部导航栏打一个圆形的洞
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Expanded(
                      flex: 1,
                      child: Container(
                        height: 52.0,
                        padding: const EdgeInsets.only(
                            left: 16, top: 0, right: 16, bottom: 10),
                        child: TextButton(
                          onPressed: () {
                            FocusScope.of(context).requestFocus(FocusNode());
                            saveUserInfo();
                          },
                          style: const ButtonStyle(
                            alignment: Alignment.center,
                            backgroundColor:
                                WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                            foregroundColor:
                                WidgetStatePropertyAll(Colors.white),
                          ),
                          child: Stack(children: [
                            SizedBox(
                              height: 45.h,
                              width: 45.w,
                              child: Align(
                                alignment: Alignment.center,
                                child: Transform.translate(
                                  offset: const Offset(-35.0, 0.0),
                                  child: loadingFlag
                                      ? Image.asset(
                                      width: 28.w,
                                      height: 25.h,
                                      alignment: Alignment.center,
                                      "assets/images/loading/loading.gif")
                                      : null,
                                ),
                              ),
                            ),
                            SizedBox(
                                height: 45.h,
                                child: Align(
                                    alignment: Alignment.center,
                                    child: Text('完成',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 18.sp,
                                            color: ColorConstant.White)))),
                          ]),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            )));
  }

  // 选择性别
  void _showGenderBottomSheet(BuildContext context) {
    //显示底部弹窗
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ), //圆角
      builder: (context) {
        return Container(
          height: 256.0,
          color: Colors.white,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _buildButtonRow(context),
              Expanded(
                child: CupertinoPicker(
                  scrollController: FixedExtentScrollController(),
                  itemExtent: 32.0, // 每个项目的尺寸
                  children: <Widget>[
                    for (int i = 0; i < genderList.length; i++)
                      Text(genderList[i]),
                  ],
                  onSelectedItemChanged: (int index) {
                    setState(() {
                      _selectedGender = index;
                    });
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildButtonRow(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        TextButton(
          onPressed: () {
            EcyRouter.pop(context, "");
          },
          child: const Text(
            "取消",
            textAlign: TextAlign.center,
            softWrap: true,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              fontStyle: FontStyle.normal,
              decoration: TextDecoration.none,
            ),
          ),
        ),
        TextButton(
          onPressed: () {
            setState(() {
              _selectedGenderController.text = genderList[_selectedGender];
              _selectedGenderIndex = _selectedGender;
            });
            EcyRouter.pop(context, "");
          },
          child: const Text(
            "确定",
            textAlign: TextAlign.center,
            softWrap: true,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w400,
              fontStyle: FontStyle.normal,
              color: Colors.pink,
              decoration: TextDecoration.none,
            ),
          ),
        ),
      ],
    );
  }

  // 选择生日
  void _showbirthdayBottomSheet(BuildContext context) {
    //显示底部弹窗
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ), //圆角
      builder: (context) {
        return ProfileBirthdayPicker(
          key: const Key("ProfileBirthdayPicker"),
          confirmPressed: (date) {
            _birthday = date.isEmpty
                ? DateUtil.getNowDateTimeFormat(DateUtil.PARAM_FORMAT_1)
                : date;
            setState(() {
              _birthdayController.text = _birthday;
            });
          },
        );
      },
    );
  }
}
